const { sh } = require('tasksfile');
const dedent = require('dedent');
const { openHBuildX, openHBuildXPro } = require('../helper');

/** @type {TaskRegister} */
module.exports = {
  name: 'appBuild',
  description: '打包工程应用',
  async register(options) {
    const { mode, doc, plat } = options;
    const VITE_APP_ENV = process.env.MODE || mode || 'production';
    if (plat) {
      // 打开 hbuild
      await openHBuildX();
      await sh(`uni build -p ${plat} -m ${VITE_APP_ENV}`, {
        async: true,
        nopipe: true,
        env: {
          NODE_ENV: process.env.NODE_ENV || 'production',
          PRO_DOCS: process.env.PRO_DOCS || Number(doc),
          VITE_APP_ENV: VITE_APP_ENV,
        },
      });
      await openHBuildXPro('build');
    } else {
      await sh(`vite build -m ${VITE_APP_ENV}`, {
        async: true,
        nopipe: true,
        env: {
          ...process.env,
          NODE_ENV: process.env.NODE_ENV || 'production',
          PRO_DOCS: process.env.PRO_DOCS || Number(doc),
        },
      });
    }
  },
  options: {
    doc: '打包文档',
    plat: '打包的平台，默认无需传入，当前仅支持uniApp %PLATFORM%：https://uniapp.dcloud.net.cn/quickstart-cli.html#%E8%BF%90%E8%A1%8C%E3%80%81%E5%8F%91%E5%B8%83uni-app',
    mode: '打包的服务：development、testb、testc、testd、teste、uat、production',
  },
  examples: dedent`
    gtask appBuild
    gtask appBuild --doc
    gtask appBuild --mode=development
    gtask appBuild --doc --mode=development
  `,
};
